package com.yntx.usercenter.common.config;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Optional;

/**
 * 租户用户上下文持有人
 *
 * @author 借力好风
 * @date 2023-04-26 22:53
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class TenantUserContextHolder {

    private static final TenantUserContextHolder DEFAULT_CTX = new TenantUserContextHolder();

    private static final TransmittableThreadLocal<TenantUserContextHolder> CTX = new TransmittableThreadLocal<>();

    /**
     * 租户ID
     */
    private String tenantId;

    /**
     * 租户内共享用户，默认共享
     */
    private Boolean isShareUser;

    /**
     * 系统ID
     */
    private String systemId;

    /**
     * 系统ID
     */
    private String systemCode;

    /**
     * 用户Token信息
     */
    private String token;

    /**
     * 用户 id
     */
    private String userId;

    /**
     * 用户 username
     */
    private String username;

    /**
     * ip地址
     */
    private String ip;


    public static TenantUserContextHolder get() {
        return Optional.ofNullable(CTX.get()).orElse(DEFAULT_CTX);
    }

    public static void set(TenantUserContextHolder ctx) {
        if (ctx == null) {
            CTX.remove();
        } else {
            CTX.set(ctx);
        }
    }

}
